package bean.managed;

import entity.CustomerAccountEntity;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.CustomerAccountEntityFacade;

import bean.session.CustomerEntityFacade;
import entity.CustomerEntity;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;

@ManagedBean(name = "customerAccountEntityController")
@SessionScoped
public class CustomerAccountEntityController extends AbstractBacking implements Serializable {

    @ManagedProperty(value = "#{customerEntityController}")
    private CustomerEntityController customerEntityController;
    private CustomerAccountEntity current;
    private CustomerEntity currentCustomer;
    private DataModel items = null;
    @EJB
    private bean.session.CustomerAccountEntityFacade ejbFacade;
    @EJB
    private CustomerEntityFacade customerFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private DataModel assignedAccountItems;

    public CustomerAccountEntityController() {
    }

    public CustomerAccountEntity getCurrent() {
        return current;
    }

    public void setCurrent(CustomerAccountEntity current) {
        System.out.println("setting current customerAccount: " + current);
        this.current = current;
    }

    public CustomerEntity getCurrentCustomer() {
        return currentCustomer;
    }

    public void setCurrentCustomer(CustomerEntity currentCustomer) {
        this.currentCustomer = currentCustomer;
    }

    public CustomerEntityController getCustomerEntityController() {
        return customerEntityController;
    }

    public void setCustomerEntityController(CustomerEntityController customerEntityController) {
        this.customerEntityController = customerEntityController;
    }

    public CustomerAccountEntity getSelected() {
        if (current == null) {
            current = new CustomerAccountEntity();
            selectedItemIndex = -1;
        }
        return current;
    }

    private CustomerAccountEntityFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (CustomerAccountEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareAccount() {
        currentCustomer = (CustomerEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Create";
    }

    public String prepareCreate() {
        current = new CustomerAccountEntity();
        selectedItemIndex = -1;
        return "Create";
    }

    public String createOrUpdate() {
        if (current.getId() == null) {
            return create();
        } else {
            return update();
        }
    }

    public String create() {
        try {
            if (current.getCreditTerm() != null) {
                current.setCreditBalance(current.getCreditTerm().getCreditLimit());
            }

            current.setCustomer(customerEntityController.getCurrent());
            current.created(getLoginPerson());
            getFacade().create(current);          

            customerEntityController.getCurrent().setCustomerAccount(current);
            customerEntityController.getCurrent().getCustomerAccount().setAssigned(true);
            customerEntityController.update();

            prepareList();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CustomerAccountEntityCreated"));
            return "NoAccountCustomersList";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (CustomerAccountEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            current.modified(getLoginPerson());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CustomerAccountEntityUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            current.getCustomer().setCustomerAccount(null);
            customerFacade.edit(current.getCustomer());
            
            current.modified(getLoginPerson());
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CustomerAccountEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    public DataModel getAssignedAccountItems() {
        //if (assignedAccountItems == null) {
        assignedAccountItems = ejbFacade.findAllAssignedAccounts();
        //}
        return assignedAccountItems;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = CustomerAccountEntity.class)
    public static class CustomerAccountEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CustomerAccountEntityController controller = (CustomerAccountEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "customerAccountEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof CustomerAccountEntity) {
                CustomerAccountEntity o = (CustomerAccountEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CustomerAccountEntityController.class.getName());
            }
        }
    }

    public CustomerAccountEntity getBlankCustomerAccount() {
        System.out.println("getting blanck customer account");
        return new CustomerAccountEntity();
    }
}
